<?php

class InsertHiveTableAction extends HiveAction {
	
	public function __construct($name, $cmd, $hiveClient) {		
		parent::__construct($name, $cmd, $hiveClient);
	}
	
	public function execute(ezcWorkflowExecution $execution) {
		$source	= CJSON::decode($execution->getVariable('source'));
		$dest	= CJSON::decode($execution->getVariable('dest'));
		
    	$tableName	= $source['storage'];
    	$select		= $source['filter']['select'];
    	$condition	= $source['filter']['condition'];
    	$params		= $source['filter']['params'];
    	
    	$newTable	= $dest['storage'];
    	
    	$this->cmd = $this->concreteParams($this->cmd, array(
    		':tableName'	=>	$tableName,
    		':newTable'		=>	$newTable,
    		':columns'		=>	$this->generateColumnList($select),
    		':conditions'	=>	$this->concreteParams($condition, $params),
    		)
    	);
 		return parent::execute($execution);
    }

    public function getResultSize() {
        $statusLog = $this->getStatus();
        $pos = strpos($statusLog, 'total_size:');
        if($pos === false) {
            return parent::getResultSize();
        }

        preg_match('@\d+@', $statusLog, $matches, 0, $pos);
        return $matches[0];
    }

    public function getResultCount() {
        $statusLog = $this->getStatus();
        $pos = strpos($statusLog, ']');
        if($pos === false) {
            return parent::getResultSize();
        }

        preg_match('@\d+@', $statusLog, $matches, 0, $pos);
        return $matches[0];
    }
    
    private function generateColumnList($select) {
    	$columns = array_keys($select);
    	return implode(',', $columns);
    }
}
